#include <string>
#include <iostream>


#include "connectingsocket.h"
#define BUFF_SIZE ( 500 )


namespace utils
{

ConnectionSocket::ConnectionSocket( int nFN ) :
m_nConnectionFD( nFN )
{
}

ConnectionSocket::~ConnectionSocket()
{
	close( m_nConnectionFD );
}

void ConnectionSocket::Send( const std::string& sInputMessage ) const
{
	int nSend = send( m_nConnectionFD, sInputMessage.c_str(), sInputMessage.size(), 0 );
	if( nSend == -1 )
	{
		throw ExceptionError( "Could not write to socket." );
	}
}


void ConnectionSocket::Receive( std::string& sInputMessage ) const
{
	char buf[ BUFF_SIZE + 1 ];

	sInputMessage = "";

	int nRecv = recv( m_nConnectionFD, buf, BUFF_SIZE, 0 );

	if( nRecv == -1 )
	{
		throw ExceptionError( "Could not read from socket." );
	}
	else if( nRecv == 0 )
	{
		throw ExceptionClosed( "Connection is closed." );
		//sInputMessage = "error";
	}
	else
	{
		buf[ nRecv ] = '\0';
		sInputMessage = buf;
	}

}

} // namespace utils

